package com.huawei.codelab.utils;

import ohos.agp.components.Image;
import ohos.app.Context;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class LoadImageUtil {
    public static void loadImg(Context context,String netImgUrl, Image image){
        TaskDispatcher globalTaskDispatcher = context.getGlobalTaskDispatcher(TaskPriority.DEFAULT);
        globalTaskDispatcher.asyncDispatch(()->{
            HttpURLConnection connection =null;
            try {
                                URL url= new URL(netImgUrl);
                //具体：
//                URLConnection urlConnection = url.openConnection();
                //简写：向上转型
                connection =(HttpURLConnection)url.openConnection();

                connection.connect();

                //从连接中获取输入流，就可以得到图片数据
                InputStream inputStream = connection.getInputStream();
                //使用IMAGESOURCE缓冲图片对象
                ImageSource imageSource = ImageSource.create(inputStream,new ImageSource.SourceOptions());

                //图片数据解码参数
               ImageSource.DecodingOptions decodingOptions= new ImageSource.DecodingOptions();
               decodingOptions.desiredPixelFormat = PixelFormat.ARGB_8888;

                //              PIXMAP对象就表示一个图片
                PixelMap pixelmap =imageSource.createPixelmap(decodingOptions);

                context.getUITaskDispatcher().asyncDispatch(()->{
                    //                将图片载入组件中
                    image.setPixelMap(pixelmap);
                    pixelmap.release();


                });
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

    }
}
